// 引入 events 模块
const events = require("node:events");

// 创建事件发送器
const eventEmitter = new events.EventEmitter({ captureRejections: true });

// 监听连接
eventEmitter.on("connection", () => {
  console.log("连接成功");
  eventEmitter.emit("data_received");
});

const receivedHandle = () => {
  console.log("数据接收成功");
};

// 监听数据接收
eventEmitter.on("data_received", receivedHandle);

// 效果等同于 on，写法不同
eventEmitter.addListener("data_received", receivedHandle);

// 移除监听事件 on | addListener
// eventEmitter.removeListener("data_received", receivedHandle);

// 移除所有/单个事件，指定事件名称，则移除该事件的所有监听器，不指定则移除所有事件
// eventEmitter.removeAllListeners("data_received");

// 设置监听事件的数量
const event = eventEmitter.setMaxListeners(1);
console.log(
  `事件数量：${event._eventsCount}. 最大监听数量：${event.getMaxListeners()}`
);

// 发送连接
eventEmitter.emit("connection");

// once: 单次监听器。只会触发一次，触发后立刻解除
eventEmitter.once("once_event", (arg) => {
  console.log("once_event: ", arg);
});

for (let i = 0; i < 2; i++) {
  eventEmitter.emit("once_event", i);
}
eventEmitter.emit("error");
console.log("执行完毕");
